var fs = require('fs');
var http = require('http');
var https = require('https');
var ejs = require('ejs');
var bodyParser = require('body-parser');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var privateKey = fs.readFileSync('ssl/private.key', 'utf8');
var certificate = fs.readFileSync('ssl/certificate.crt', 'utf8');

var credentials = {
  key: privateKey,
  cert: certificate
};
var express = require('express');
var app = express();

// your express configuration here

// 使用 session 中间件
app.use(session({
  secret: 'secret', // 对session id 相关的cookie 进行签名
  resave: true,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie: {
    maxAge: 1000 * 60 * 10, // 设置 session 的有效时间，单位毫秒
  },
  store: new MongoStore({
    url: 'mongodb://localhost:27017/expresshttps-session'
  })
}));

app.use(bodyParser());

app.engine('html', ejs.__express); // 给指定拓展名的模板文件注册模板引擎
app.set('views', './view'); // 视图模板所在目录
app.set('view engine', 'html'); // 设置模板拓展名

// 启动测试
app.use('/hello', function(req, res, next) {
  res.send('hello world');
});

// 登陆页面
app.get('/login', function(req, res, next) {
  res.render('index');
});

// 用户登陆
app.post('/login', function(req, res, next) {
  if ('user' == req.body.username && '123456' == req.body.password) {
    req.session.user = 'user';
    res.redirect('/test');
  } else {
    res.redirect('/login');
  }
});

// 测试用户是否已登陆
app.use('/test', function(req, res, next) {
  if (!req.session.user) {
    res.redirect('/login');
  } else {
    res.send('login success!');
  }
});

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(9080, function() {
  var host = httpServer.address().address;
  var port = httpServer.address().port;
  console.log('ExpressHttps app listening at http://%s:%s', host, port);
});
httpsServer.listen(443, function() {
  var host = httpsServer.address().address;
  var port = httpsServer.address().port;
  console.log('ExpressHttps app listening at https://%s:%s', host, port);
});